package tech.mhuang.ext.netty.sample.client;

import tech.mhuang.core.close.BaseCloseable;
import tech.mhuang.ext.netty.client.AbstractNettyClient;
import tech.mhuang.ext.netty.sample.handler.TestClientChannelInitializerHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author mHuang
 * @version V1.0.0
 * @Description netty 客户端 Demo
 * @date 2015年7月16日 下午2:55:36
 */
public class TestNettyClient extends AbstractNettyClient implements BaseCloseable {

    private static final long serialVersionUID = 1L;

    public static Channel channel = null;

    @Override
    public void connect(String host, int port) {
        //config thread pool
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            //config client aotu property
            Bootstrap b = new Bootstrap();
            b.group(group).channel(NioSocketChannel.class).handler(new TestClientChannelInitializerHandler());
            // Start the client.
            ChannelFuture f = b.connect(host, port).sync();
            // Wait until the connection is closed.
            f.channel().closeFuture().sync();

        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            group.shutdownGracefully();
        }
    }

    @Override
    public void connect() {
        connect(host, port);
    }


    @Override
    public void close() {
        TestNettyClient.channel.close();
    }

    class ClientTask implements Runnable {
        /**
         * 日志对象
         */
        protected Logger logger = LoggerFactory.getLogger(ClientTask.class);

        @Override
        public void run() {
            try {
                while (true) {
                    if (null != TestNettyClient.channel) {
                        if (TestNettyClient.channel.isActive() && TestNettyClient.channel.isWritable()) {
//							NettyClient.channel.writeAndFlush("我是客户端发的消息.....");
                        } else { //重连
                            logger.error("客户端重连....");
                            TestNettyClient.channel.close();
                            new TestNettyClient().connect();
                        }
                    }
                    Thread.sleep(10000);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
